package com.atguigu.tingshu.user.login.domain;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.constant.TingShuMqConstants;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.service.RabbitmqService;
import com.atguigu.tingshu.vo.base.user.UserInfo;
import com.atguigu.tingshu.user.login.annotation.DifWaysLogin;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.vo.user.LoginVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@DifWaysLogin
public class WechatLogin implements ILogin {
    @Resource
    private WxMaService wxMaService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RabbitmqService rabbitmqService;
    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public Map<String, String> login(LoginVo loginVo) {
        //调用接口获取sessionInfo信息
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(loginVo.getCode());
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //获取openId
        String openid = sessionInfo.getOpenid();
        //若openId存在，则根据openId查询用户信息
        if (StringUtils.isNotBlank(openid)) {
            //根据openId查询用户信息
            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
            if (userInfo == null) {
                //如果用户信息不存在，则注册用户
                userInfo = new UserInfo();
                userInfo.setWxOpenId(openid);
                userInfo.setNickname("用户" + System.currentTimeMillis());
                userInfo.setAvatarUrl("https://ww1.sinaimg.cn/mw690/00822bhDly1hr1a9ibrknj30sg0sg77d.jpg");
                userInfo.setStatus(SystemConstant.USER_STATUS_NORMAL);
                userInfoMapper.insert(userInfo);
                Long userInfoId = userInfo.getId();

                //使用rabbitmq发送消息
                rabbitmqService.sendMqMsg(TingShuMqConstants.TING_SHU_USER_EXCHANGE, TingShuMqConstants.TING_SHU_USER_ROUTING_KEY, userInfoId, true, 3);
            }
            String token = UUID.randomUUID().toString();
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo, userInfoVo);
            redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
            return Map.of("token", token);
        } else {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
    }
}
